package com.cmcc.shared.network.interceptor

import com.alibaba.android.arouter.launcher.ARouter.logger
import com.cmcc.shared.SdkManager
import okhttp3.*
import java.io.IOException

class HeaderInterceptor : Interceptor {
    private val headerSet = LinkedHashMap<String, String>()

    init {
        headerSet["Accept"] = "application/json"
    }

    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response? {

        val requestOrigin = chain.request()
        val headersOrigin = requestOrigin.headers()
        val builder = headersOrigin.newBuilder()
        for ((key, value) in headerSet) {
            builder.set(key, value)
        }
        val headers = builder.build()
        val request = requestOrigin.newBuilder().headers(headers).build()
        //创建 mediaType 和 content
        var mediaType: MediaType? = MediaType.parse("application/json;charset=UTF-8");

        val content = "\"{\"code\": 404, \"msg\": \"Net Error\", \"data\": \"null\"}\""
        var response: Response
        try {
            response = chain.proceed(request)
            if (response.body() == null) {
                val builder = Response.Builder()
                    .headers(request.headers())
                    .code(100)
                    .message("Net Error")
                    .body(ResponseBody.create(mediaType, content))
                    .protocol(Protocol.HTTP_1_1)
                    .request(request)
                response = builder.build()
                SdkManager.netWorkListener?.netError()

                return  response;
            }
        } catch (e: Exception) {

            val builder = Response.Builder()
                .headers(request.headers())
                .code(100)
                .message("Net Error")
                .body(ResponseBody.create(mediaType, content))
                .protocol(Protocol.HTTP_1_1)
                .request(request)
            response = builder.build()

            SdkManager.netWorkListener?.netError()

            return response
        }
        return response

    }

    fun addHeader(key: String, value: String) {
        headerSet[key] = value
    }

    fun removeHeader(key: String) {
        headerSet.remove(key)
    }
}